package com.hmyd.hmyd_android.fragment;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.adapter.InvestmentListTypeAdapter;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dialog.IdentifyingDialog;
import com.hmyd.hmyd_android.dialog.IdentifyingDialogListener;
import com.hmyd.hmyd_android.dto.Deposit;
import com.hmyd.hmyd_android.dto.Info;
import com.hmyd.hmyd_android.dto.Investment;
import com.hmyd.hmyd_android.dto.InvestmentCapitalPage;
import com.hmyd.hmyd_android.ui.BillTypeDetailActivity;
import com.hmyd.hmyd_android.ui.InvestmentTypeDetailActivity;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.Utils;
import com.hmyd.hmyd_android.view.listview.XListView;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class InvestmentTypeFragment extends BasicFragmentList {
	
	private XListView mList;
	private InvestmentListTypeAdapter mInestmentListAdapter;
	
	private String mType;
	
	private final int REFRESH = 1;
	private final int LOADMORE = 2;
	public static final int DODEPOSIT = 3;
	private final int CANCELORDER = 4;
	
	protected boolean hasMore = false;
	private String cursorId;
	
	private List<Investment> listData = new ArrayList<Investment>();
	
	private TextView mCount;
	private TextView mPrincipal;
	private TextView mInterest;
	
	View investmentLayout = null;
	
	private String tradeNo;
	private String mCancelId;
	private int mCancelPosition;
	
//	 private Toast toast = null;
	
	public InvestmentTypeFragment(){
		
	}
	
	public static InvestmentTypeFragment newInstance(String type) {
		InvestmentTypeFragment myFragment = new InvestmentTypeFragment();

        Bundle args = new Bundle();
        args.putString("type", type);
        myFragment.setArguments(args);

        return myFragment;
    }
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		mType = getArguments().getString("type");
		
		if(investmentLayout==null){
			investmentLayout = inflater.inflate(R.layout.fragment_investment_type_list, container, false);
        
			initViews(investmentLayout);
			initListener();
		}
		
		//缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
		ViewGroup parent = (ViewGroup) investmentLayout.getParent();
        if (parent != null) {
            parent.removeView(investmentLayout);
        } 
		
		return investmentLayout;
	}
	
	public XListView getXList() {
		return mList;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if (!isLoading && listData.size() == 0) {
			RequestParams params = new RequestParams();
			params.addBodyParameter("category", mType);
			
			onRequest(REFRESH, UrlConstant.INVESTMENTLIST, HttpMethod.GET, params);
		}
	}
	
	private void initViews(View rootLayout){
		mList = (XListView) rootLayout.findViewById(R.id.list);
		mList.setPullRefreshEnable(true); // 允许下拉刷新
		mList.setPullLoadEnable(false); // 禁止加载更多
		mList.setAutoLoadEnable(false); // 禁止自动加载
		mList.setXListViewListener(this);// 加载监听
		
		mInestmentListAdapter = new InvestmentListTypeAdapter(getActivity(), listData, mType, this);
		mList.setAdapter(mInestmentListAdapter);
		
		mCount = (TextView) rootLayout.findViewById(R.id.count);
		mPrincipal = (TextView) rootLayout.findViewById(R.id.principal);
		mInterest = (TextView) rootLayout.findViewById(R.id.interest);
	}
	
	@Override
	public void onRefresh() {
		super.onRefresh();
		RequestParams params = new RequestParams();
		params.addBodyParameter("category", mType);

		onRequest(REFRESH, UrlConstant.INVESTMENTLIST, HttpMethod.GET, params);
	}

	@Override
	public void onLoadMore() {
		super.onLoadMore();

		RequestParams params = new RequestParams();
		params.addBodyParameter("lastCursor", cursorId);
		params.addBodyParameter("category", mType);
		onRequest(LOADMORE, UrlConstant.INVESTMENTLIST, HttpMethod.GET, params);
	}
	
	public void onRequest(final int postId,final String url,HttpMethod methodType,RequestParams params, int position){
		mCancelId = listData.get(position).itemRecordId;
		mCancelPosition = position;
		
		onRequest(InvestmentTypeFragment.DODEPOSIT, UrlConstant.SENDCANCELORDERVERIFYCODE, HttpMethod.GET, null);
	}
	
	private String result;
	public void onPostSuccess(int postId, String result) {
		super.onPostSuccess(postId, result);
		
		// 防止多次加载重复数据
		if (!TextUtils.isEmpty(this.result) && this.result.equals(result)) {

			Log.i(" this.result ", " ------->>>>> result rep");
			return;
		}
		
		switch (postId) {
		case DODEPOSIT:
			Gson gson = new Gson();
			java.lang.reflect.Type type3 = new TypeToken<Deposit>() {}.getType();
			Deposit deposit = gson.fromJson(result, type3);
			tradeNo = deposit.verifyCodeId;
			
			MyToast.showToast(getActivity(), "验证码已发送，请注意查收");
			
			IdentifyingDialog cd = new IdentifyingDialog(getActivity(),R.style.calculatorDialog, new IdentifyingDialogListener() {
				@Override
				public void getIdentifyind(String validCode) {
					RequestParams params = new RequestParams();
					params.addBodyParameter("itemRecordId",mCancelId);
					params.addBodyParameter("verifyCodeId", tradeNo);
					params.addBodyParameter("verifyCode", validCode);
					onRequest(CANCELORDER, UrlConstant.CANCELORDER, HttpMethod.POST, params);
					
				}
			});
			cd.show();
			
			return;
			
		case CANCELORDER:
			Gson gson2 = new Gson();
			java.lang.reflect.Type type = new TypeToken<Info>() {}.getType();
			Info info = gson2.fromJson(result, type);
			
			if("Ok".equals(info.status)){
				MyToast.showHMToast(getActivity(), true, info.info);
				
				listData.get(mCancelPosition).isCanceled = true;
				mInestmentListAdapter.notifyDataSetChanged();
			}
			
			return;

		default:
			break;
			
			
		}
		
		Gson gson = new Gson();
		java.lang.reflect.Type type2 = new TypeToken<InvestmentCapitalPage<Investment>>() {}.getType();
		InvestmentCapitalPage<Investment> page = gson.fromJson(result, type2);
		hasMore = page.investRecords.hasMore;
		if(page!=null && page.investRecords.records!=null){
			switch (postId) {
			case REFRESH:
				listData.clear();
				listData.addAll(page.investRecords.records);
				mCount.setText(Utils.amountConversionFormat(page.totalCount));
				mPrincipal.setText(Utils.amountConversionFormat(page.principal));
				mInterest.setText(Utils.amountConversionFormat(page.interest));
				break;
			case LOADMORE:
				listData.addAll(page.investRecords.records);
				break;
			default:
				break;
			}
			
			if(listData.size()>0){
				cursorId = listData.get(listData.size()-1).cursorId;
			}else{
				cursorId = null;
			}
			
			mInestmentListAdapter.notifyDataSetChanged();
		}
		
		if(getXList()!=null && hasMore){
			getXList().setPullLoadEnable(true);
		}else if(getXList()!=null && !hasMore){
			getXList().setPullLoadEnable(false);
		}
	}

	public void onPostFailure(int postId, String msg) {
		super.onPostFailure(postId, msg);
		
		switch (postId) {
			
		case CANCELORDER:
			Gson gson2 = new Gson();
			java.lang.reflect.Type type = new TypeToken<Info>() {}.getType();
			Info info = gson2.fromJson(msg, type);
			
			if("Fail".equals(info.status)){
				MyToast.showHMToast(getActivity(), false, info.info);
			}
			return;

		default:
			break;
			
			
		}

		if(getXList()!=null && hasMore){
			getXList().setPullLoadEnable(true);
		}else if(getXList()!=null && !hasMore){
			getXList().setPullLoadEnable(false);
		}
	}
	
	private void initListener(){
		mList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if("investing".equals(mType)){
					MyToast.showToast(getActivity(), "满标后次日开始计息");
					return;
				}
				if(!TextUtils.isEmpty(mType)&&listData.size()>=(position)){
					// 个人票据详情跳转
					if("grpj".equals(listData.get(position-1).type)) {
						startActivity(BillTypeDetailActivity.getIntent(getActivity(), listData.get(position-1).itemRecordId));
						return;
					}
					startActivity(InvestmentTypeDetailActivity.getIntent(getActivity(), listData.get(position-1).itemRecordId));
				}
			}

		});
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		result = null;
	}
	
}
